import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from "@/views/Login"

import store from '@/store'
import storage from '@/store/storage'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: {
            keepalive: false
        }
    },
    {
        path: '/about',
        name: 'About',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
    },
    {
        path: '/notice',
        name: 'Notice',
        component: () => import(/* webpackChunkName: "notice" */ '../views/Notice.vue')
    },
    {
        path: '/officeEdit',
        name: 'OfficeEdit',
        component: () => import(/* webpackChunkName: "notice" */ '../views/OfficeEdit.vue')
    },
    {
        path: '/officeView',
        name: 'OfficeView',
        component: () => import(/* webpackChunkName: "notice" */ '../views/OfficeView.vue')
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

// 设置路由守卫，在进页面之前，判断有token，才进入页面，否则返回登录页面
if (storage.get("token")) {
    store.commit("set_token", storage.get("token"));
}
router.beforeEach((to, from, next) => {
    // 判断要去的路由有没有requiresAuth
    // to.matched.some(r => r.meta.requireAuth) or to.meta.requiresAuth
    if (to.matched.some(r => r.meta.requireAuth)) {
        if (store.state.token) {
            next(); //有token,进行request请求，后台还会验证token
        } else {
            next({
                path: "/login",
                // 将刚刚要去的路由path（却无权限）作为参数，方便登录成功后直接跳转到该路由，这要进一步在登陆页面判断
                query: {redirect: to.fullPath}
            });
        }
    } else {
        next(); //如果无需token,那么随它去吧
    }
});

export default router
